from flask import Blueprint, jsonify, request, current_app, render_template, send_from_directory, Response, stream_with_context
from werkzeug.utils import secure_filename
import os
from datetime import datetime
from core.plugin_manager import PluginManager
from core.ai_service import AIService
from models.database import db, User, Settings
import json

# API蓝图
api_bp = Blueprint('api', __name__)

# 页面路由蓝图
page_bp = Blueprint('page', __name__)

# 确保上传目录存在
def ensure_upload_dir():
    upload_dir = current_app.config['UPLOAD_DIR']
    if not os.path.exists(upload_dir):
        os.makedirs(upload_dir)
    return upload_dir

# 保存上传的头像
def save_avatar(file):
    if not file:
        return None
    
    filename = secure_filename(file.filename)
    # 生成唯一文件名
    name, ext = os.path.splitext(filename)
    unique_filename = f"{name}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}{ext}"
    
    upload_dir = ensure_upload_dir()
    file_path = os.path.join(upload_dir, unique_filename)
    file.save(file_path)
    
    # 返回可访问的URL
    return f"/uploads/{unique_filename}"

# 页面路由
@page_bp.route('/')
def index():
    return render_template('index.html')

@page_bp.route('/settings')
def settings():
    return render_template('settings.html')

@page_bp.route('/market')
def market():
    return render_template('market.html')

# 插件静态文件路由
@page_bp.route('/plugins/<plugin_id>/<path:filename>')
def plugin_static(plugin_id, filename):
    """提供插件静态文件访问"""
    # 检查是否是 assets 目录下的文件
    if filename.startswith('assets/'):
        # 直接使用完整路径
        plugin_path = os.path.join(current_app.config['PLUGIN_DIR'], plugin_id)
        return send_from_directory(plugin_path, filename)
    else:
        # 非 assets 目录下的文件，只允许访问根目录文件
        plugin_path = os.path.join(current_app.config['PLUGIN_DIR'], plugin_id)
        return send_from_directory(plugin_path, filename)

# 插件页面路由
@page_bp.route('/plugins/<plugin_id>')
def plugin_page(plugin_id):
    """提供插件页面访问"""
    plugin_path = os.path.join(current_app.config['PLUGIN_DIR'], plugin_id)
    
    # 读取插件的index.html
    with open(os.path.join(plugin_path, 'index.html'), 'r', encoding='utf-8') as f:
        content = f.read()
        
    # 注入Font Awesome
    if '<head>' in content:
        font_awesome = '<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">'
        content = content.replace('<head>', f'<head>{font_awesome}')
    
    # 注入返回按钮的样式
    if '</head>' in content:
        floating_css = '<link rel="stylesheet" href="/static/css/floating-button.css">'
        content = content.replace('</head>', f'{floating_css}</head>')
    
    # 注入返回按钮的HTML
    if '</body>' in content:
        floating_btn = '''
        <div class="floating-home-btn" onclick="window.location.href='/'">
            <i class="fas fa-home"></i>
        </div>
        '''
        content = content.replace('</body>', f'{floating_btn}</body>')
    
    return content

# 用户上传文件访问路由
@page_bp.route('/uploads/<path:filename>')
def uploaded_file(filename):
    """提供上传文件的访问"""
    return send_from_directory(current_app.config['UPLOAD_DIR'], filename)

# API路由
@api_bp.route('/users', methods=['GET'])
def get_users():
    """获取所有用户列表"""
    users = User.query.all()
    return jsonify({
        'status': 'success',
        'data': [user.to_dict() for user in users]
    })

@api_bp.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
    """获取单个用户信息"""
    user = User.query.get_or_404(user_id)
    return jsonify({
        'status': 'success',
        'data': user.to_dict()
    })

@api_bp.route('/users', methods=['POST'])
def create_user():
    """创建新用户"""
    avatar_url = None
    if 'avatar' in request.files:
        avatar_url = save_avatar(request.files['avatar'])
    
    user = User(
        username=request.form.get('username'),
        gender=request.form.get('gender'),
        grade=request.form.get('grade'),
        avatar=avatar_url
    )
    db.session.add(user)
    db.session.commit()
    
    return jsonify({
        'status': 'success',
        'data': user.to_dict()
    })

@api_bp.route('/users/<int:user_id>', methods=['PUT', 'POST'])
def update_user(user_id):
    """更新用户信息"""
    user = User.query.get_or_404(user_id)
    
    # 处理头像上传
    if 'avatar' in request.files:
        avatar_file = request.files['avatar']
        if avatar_file and avatar_file.filename:  # 确保文件存在且有文件名
            avatar_url = save_avatar(avatar_file)
            if avatar_url:
                # 删除旧头像
                if user.avatar and not user.avatar.startswith('http'):
                    old_avatar_path = os.path.join(
                        current_app.config['UPLOAD_DIR'],
                        os.path.basename(user.avatar)
                    )
                    if os.path.exists(old_avatar_path):
                        os.remove(old_avatar_path)
                user.avatar = avatar_url
    
    # 更新其他字段
    form_data = request.form
    if form_data:  # 如果是 form-data 请求
        if 'username' in form_data:
            user.username = form_data['username']
        if 'gender' in form_data:
            user.gender = form_data['gender']
        if 'grade' in form_data:
            user.grade = form_data['grade']
    else:  # 如果是 JSON 请求
        data = request.get_json(silent=True) or {}
        if 'username' in data:
            user.username = data['username']
        if 'gender' in data:
            user.gender = data['gender']
        if 'grade' in data:
            user.grade = data['grade']
        
    db.session.commit()
    return jsonify({
        'status': 'success',
        'data': user.to_dict()
    })

@api_bp.route('/users/<int:user_id>', methods=['DELETE', 'OPTIONS'])
def delete_user(user_id):
    """删除用户"""
    if request.method == 'OPTIONS':
        # 处理预检请求
        response = current_app.make_default_options_response()
        response.headers['Access-Control-Allow-Methods'] = 'DELETE'
        return response
        
    user = User.query.get_or_404(user_id)
    
    # 删除用户头像
    if user.avatar and not user.avatar.startswith('http'):
        avatar_path = os.path.join(
            current_app.config['UPLOAD_DIR'],
            os.path.basename(user.avatar)
        )
        if os.path.exists(avatar_path):
            os.remove(avatar_path)
    
    # 删除用户
    db.session.delete(user)
    db.session.commit()
    
    return jsonify({
        'status': 'success',
        'message': '用户已删除'
    })

@api_bp.route('/users/<int:user_id>/settings', methods=['GET'])
def get_user_settings(user_id):
    """获取用户设置"""
    settings = Settings.query.filter_by(user_id=user_id).first_or_404()
    return jsonify({
        'status': 'success',
        'data': settings.to_dict()
    })

@api_bp.route('/users/<int:user_id>/settings', methods=['PUT'])
def update_user_settings(user_id):
    """更新用户设置"""
    settings = Settings.query.filter_by(user_id=user_id).first_or_404()
    data = request.json
    
    if 'api_key' in data:
        settings.api_key = data['api_key']
    if 'api_model' in data:
        settings.api_model = data['api_model']
        
    db.session.commit()
    return jsonify({
        'status': 'success',
        'data': settings.to_dict()
    })

@api_bp.route('/plugins', methods=['GET'])
def get_plugins():
    """获取已安装的插件列表"""
    return jsonify({
        'status': 'success',
        'data': current_app.plugin_manager.get_plugins()
    })

@api_bp.route('/plugins/<plugin_id>', methods=['GET'])
def get_plugin(plugin_id):
    """获取指定插件的详细信息"""
    plugin = current_app.plugin_manager.get_plugin_by_id(plugin_id)
    if plugin:
        return jsonify({
            'status': 'success',
            'data': plugin
        })
    else:
        return jsonify({
            'status': 'error',
            'message': 'Plugin not found'
        }), 404

@api_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    return jsonify({
        'status': 'success',
        'message': 'Service is running'
    })

@api_bp.route('/settings', methods=['GET'])
def get_settings():
    """获取系统设置"""
    settings = Settings.query.first()
    if not settings:
        settings = Settings()
        db.session.add(settings)
        db.session.commit()
    return jsonify({
        'status': 'success',
        'data': settings.to_dict()
    })

@api_bp.route('/settings', methods=['PUT'])
def update_settings():
    """更新系统设置"""
    settings = Settings.query.first()
    if not settings:
        settings = Settings()
        db.session.add(settings)
    
    data = request.json
    if 'api_key' in data:
        settings.api_key = data['api_key']
    if 'api_model' in data:
        settings.api_model = data['api_model']
        
    db.session.commit()
    return jsonify({
        'status': 'success',
        'data': settings.to_dict()
    })

@api_bp.route('/plugins/<plugin_id>/enable', methods=['POST'])
def enable_plugin(plugin_id):
    """启用插件"""
    if current_app.plugin_manager.enable_plugin(plugin_id):
        return jsonify({
            'status': 'success',
            'message': 'Plugin enabled successfully'
        })
    return jsonify({
        'status': 'error',
        'message': 'Failed to enable plugin'
    }), 400

@api_bp.route('/plugins/<plugin_id>/disable', methods=['POST'])
def disable_plugin(plugin_id):
    """禁用插件"""
    if current_app.plugin_manager.disable_plugin(plugin_id):
        return jsonify({
            'status': 'success',
            'message': 'Plugin disabled successfully'
        })
    return jsonify({
        'status': 'error',
        'message': 'Failed to disable plugin'
    }), 400

@api_bp.route('/plugins/<plugin_id>/config', methods=['GET'])
def get_plugin_config(plugin_id):
    """获取插件配置"""
    config = current_app.plugin_manager.get_plugin_config(plugin_id)
    if config is not None:
        return jsonify({
            'status': 'success',
            'data': config
        })
    return jsonify({
        'status': 'error',
        'message': 'Plugin not found'
    }), 404

@api_bp.route('/plugins/<plugin_id>/config', methods=['PUT'])
def update_plugin_config(plugin_id):
    """更新插件配置"""
    config = request.json
    if current_app.plugin_manager.update_plugin_config(plugin_id, config):
        return jsonify({
            'status': 'success',
            'message': 'Plugin config updated successfully'
        })
    return jsonify({
        'status': 'error',
        'message': 'Failed to update plugin config'
    }), 400

@api_bp.route('/ai/chat', methods=['POST'])
def ai_chat():
    """AI聊天接口"""
    data = request.json
    if not data or 'messages' not in data:
        return jsonify({
            'status': 'error',
            'message': 'Messages are required'
        }), 400
        
    try:
        # 获取参数
        messages = data['messages']
        stream = data.get('stream', False)
        api_key = data.get('api_key')
        model = data.get('model')
        
        # 创建AI服务实例
        ai_service = AIService(api_key=api_key, model=model)
        
        # 发送请求
        if stream:
            def generate():
                response = ai_service.chat(messages, stream=True)
                for chunk in ai_service.stream_handler(response):
                    yield f"data: {json.dumps(chunk)}\n\n"
                    
            return Response(
                stream_with_context(generate()),
                mimetype='text/event-stream'
            )
        else:
            response = ai_service.chat(messages)
            return jsonify({
                'status': 'success',
                'data': response
            })
            
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500
 